package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.BagUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;

    @Transactional
    public void saveWithDish(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);

        //向套餐表插入数据
        setmealMapper.insert(setmeal);

        //获取生成的套餐id
        Long setmealId = setmeal.getId();

        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
        });

        //保存套餐和菜品的关联关系
        for(SetmealDish setmealDish : setmealDishes){
            setmealDishMapper.insert(setmealDish);
        }
    }

    @Override
    public PageResult page(SetmealPageQueryDTO setmealPageQueryDTO) {
        // 接受setmealPageQueryDTO类型 转为setmealPageQueryVo类型
        Integer page = setmealPageQueryDTO.getPage();
        Integer pageSize = setmealPageQueryDTO.getPageSize();
        Integer categoryId = setmealPageQueryDTO.getCategoryId();
        String name = setmealPageQueryDTO.getName();
        Integer status = setmealPageQueryDTO.getStatus();
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        if(name != null && name != ""){
            page = 1;
            queryWrapper.like("name", name);
        }
        if(categoryId != null && categoryId != 0){
            page = 1;
            queryWrapper.eq("category_id", categoryId);
        }
        if(status != null && status != 0){
            page = 1;
            queryWrapper.eq("status", status);
        }
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        setmealMapper.selectPage(setmealPage, queryWrapper).getRecords();
        List<Setmeal> setmealList = setmealPage.getRecords();
        List<SetmealVO> setmealVOList = new ArrayList<>();
        Long count = setmealMapper.selectCount(queryWrapper);
        Page<SetmealVO> pageVO = new Page<>();
        List<SetmealVO> voList = new ArrayList<>();
        for(Setmeal setmeal : setmealList){
            SetmealVO setmealVO = new SetmealVO();
            QueryWrapper<SetmealDish> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("setmeal_id", setmeal.getId());
            List<SetmealDish> setmealDishes = setmealDishMapper.selectList(queryWrapper1);
            BeanUtils.copyProperties(setmeal, setmealVO);
            setmealVO.setSetmealDishes(setmealDishes);
            setmealVO.setCategoryName(categoryMapper.selectById(setmeal.getCategoryId()).getName());
            voList.add(setmealVO);
        }
        pageVO.setRecords(voList);

//        System.out.println(pageVO.getRecords());

        return new PageResult(count, pageVO.getRecords());
    }

    @Override
    public void deleteBatch(List<Long> ids) {
        for(Long id : ids){
            if(setmealMapper.selectById(id).getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        }

        setmealMapper.deleteBatchIds(ids);
        for(Long id : ids){
            setmealDishMapper.deleteById(new QueryWrapper<SetmealDish>().eq("setmeal_id", id));
        }
    }

    @Override
    public SetmealVO getByIdWithDish(Long id) {
        Setmeal setmeal = setmealMapper.selectById(id);
        List<SetmealDish> setmealDishes = setmealDishMapper.selectList(new QueryWrapper<SetmealDish>().eq("setmeal_id", id));

        SetmealVO setmealVO = new SetmealVO();
        BeanUtils.copyProperties(setmeal, setmealVO);
        setmealVO.setSetmealDishes(setmealDishes);

        return setmealVO;
    }

    @Override
    @Transactional
    public void update(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        Long setmealId = setmealDTO.getId();
        setmealMapper.updateById(setmeal);
        setmealDishMapper.delete(new QueryWrapper<SetmealDish>().eq("setmeal_id", setmealId));
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
        });
        //3、重新插入套餐和菜品的关联关系，操作setmeal_dish表，执行insert
        for(SetmealDish setmealDish : setmealDishes){
            setmealDishMapper.insert(setmealDish);
        }
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        //起售套餐时，判断套餐内是否有停售菜品，有停售菜品提示"套餐内包含未启售菜品，无法启售"
        if(status == StatusConstant.ENABLE){
            //select a.* from dish a left join setmeal_dish b on a.id = b.dish_id where b.setmeal_id = ?
            QueryWrapper<SetmealDish> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("setmeal_id", id);
            List<SetmealDish> setmealDishesList = setmealDishMapper.selectList(queryWrapper);
            if(setmealDishesList != null && !setmealDishesList.isEmpty()){
                setmealDishesList.forEach(setmealDish -> {
                    Long dishId = setmealDish.getDishId();
                    if(StatusConstant.DISABLE == dishMapper.selectById(dishId).getStatus()){
                        throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                    }
                });
            }
        }

        Setmeal setmeal = Setmeal.builder()
                .id(id)
                .status(status)
                .build();
        UpdateWrapper<Setmeal> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        setmealMapper.update(setmeal, updateWrapper);
    }

    @Override
    public List<Setmeal> list(Setmeal setmeal) {
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        if(setmeal.getName() != null){
            queryWrapper.like("name", setmeal.getName());
        }
        if(setmeal.getCategoryId() != null){
            queryWrapper.eq("category_id", setmeal.getCategoryId());
        }
        if(setmeal.getStatus() != null){
            queryWrapper.eq("status", setmeal.getStatus());
        }
        return setmealMapper.selectList(queryWrapper);
    }

    @Override
    public List<DishItemVO> getDishItemById(Long id) {
        QueryWrapper<SetmealDish> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("setmeal_id", id);
        List<SetmealDish> setmealDishes = setmealDishMapper.selectList(queryWrapper);
        List<DishItemVO> dishItemVOList = new ArrayList<>();
        for(SetmealDish setmealDish : setmealDishes) {
            DishItemVO dishItemVO = new DishItemVO();
            dishItemVO.setCopies(setmealDish.getCopies());
            dishItemVO.setName(setmealDish.getName());
            dishItemVO.setDescription(dishMapper.selectById(setmealDish.getDishId()).getDescription());
            dishItemVO.setImage(dishMapper.selectById(setmealDish.getDishId()).getImage());
            dishItemVOList.add(dishItemVO);
        }
        return dishItemVOList;
    }
}
